﻿using System.Collections.Generic;
using System.Text;
using PacketRush.Core;

namespace PacketRush.Services.Messaging
{
    public class ServerMessagingService : INetService
    {
        private Queue<TextMessage> _Messages = new Queue<TextMessage>(16);
        public Queue<TextMessage> Messages
        {
            get
            {
                return _Messages;
            }
        }

        private Queue<Packet> _OutgoingPackets = new Queue<Packet>(16);

        public void DeliverPacket(Packet packet)
        {
            PacketReader reader = new PacketReader(packet);
            string message = reader.ReadString(Encoding.UTF8);
            _Messages.Enqueue(new TextMessage() { ConnectionId = packet.SenderId, Message = message });

            // Relay to all clients but the sender
            packet.TargetId = packet.SenderId;
            packet.SendToAllButTarget = true;
            _OutgoingPackets.Enqueue(packet);
        }

        public Packet CollectPacket()
        {
            if (_OutgoingPackets.Count > 0)
            {
                return _OutgoingPackets.Dequeue();
            }

            return null;
        }
    }
}
